// 权限验证工具
export const permissionUtils = {
  // 检查是否有指定权限
  hasPermission(permission) {
    try {
      const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]')
      return userPermissions.includes(permission)
    } catch (error) {
      console.error('权限检查失败:', error)
      return false
    }
  },

  // 检查是否有任意一个权限
  hasAnyPermission(permissions) {
    return permissions.some(permission => this.hasPermission(permission))
  },

  // 检查是否有所有权限
  hasAllPermissions(permissions) {
    return permissions.every(permission => this.hasPermission(permission))
  },

  // 检查是否有指定资源和操作的权限
  hasResourcePermission(resource, action) {
    const permission = `${resource}:${action}`
    return this.hasPermission(permission)
  },

  // 获取用户权限列表
  getUserPermissions() {
    try {
      return JSON.parse(localStorage.getItem('userPermissions') || '[]')
    } catch (error) {
      console.error('获取用户权限失败:', error)
      return []
    }
  },

  // 设置用户权限
  setUserPermissions(permissions) {
    localStorage.setItem('userPermissions', JSON.stringify(permissions))
  },

  // 清除用户权限
  clearUserPermissions() {
    localStorage.removeItem('userPermissions')
  },

  // 检查是否为超级管理员
  isSuperAdmin() {
    return this.hasPermission('SUPER_ADMIN')
  },

  // 检查是否为系统管理员
  isAdmin() {
    return this.hasPermission('ADMIN')
  }
}

// Vue指令：权限控制
export const permissionDirective = {
  inserted(el, binding) {
    const { value } = binding
    if (value && !permissionUtils.hasPermission(value)) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  },
  update(el, binding) {
    const { value } = binding
    if (value && !permissionUtils.hasPermission(value)) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

// Vue混入：权限检查方法
export const permissionMixin = {
  methods: {
    hasPermission(permission) {
      return permissionUtils.hasPermission(permission)
    },
    hasAnyPermission(permissions) {
      return permissionUtils.hasAnyPermission(permissions)
    },
    hasAllPermissions(permissions) {
      return permissionUtils.hasAllPermissions(permissions)
    },
    hasResourcePermission(resource, action) {
      return permissionUtils.hasResourcePermission(resource, action)
    }
  }
}
